<template>
    <div>
        <el-form :model="ruleForm2" status-icon :rules="rules2" ref="ruleForm2" label-width="100px"
                 class="demo-ruleForm">
            <el-form-item label="题目" prop="p1">
                <el-input type="textarea" v-model="ruleForm2.content" :rows="5" auto-complete="off"></el-input>
            </el-form-item>
            <el-form-item label="类型">
                <el-radio-group v-model="ruleForm2.type">
                    <el-radio label="1">单选</el-radio>
                    <el-radio label="2">多选</el-radio>
                    <el-radio label="3">判断</el-radio>
                    <el-radio label="4">填空</el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item label="选项" v-if="ruleForm2.type==1||ruleForm2.type==2">
                <template v-if="ruleForm2.type==1">
                    <template v-for="(v,index) in ruleForm2.option">
                        <el-input placeholder="请输入选项内容" v-model="v.val">
                            <template slot="prepend">
                                <el-radio v-model="ruleForm2.answer" :label="v.key"></el-radio>
                            </template>
                            <el-button slot="append" icon="el-icon-delete" style="color: red;" @click="del(v,index)"></el-button>
                        </el-input>
                    </template>
                    <i class="el-icon-circle-plus-outline"
                       style="font-size: 26px;color: #66b1ff;margin-top: 10px;" @click="pushAns"></i>
                    <div>正确答案：{{ruleForm2.answer}}</div>
                </template>
                <template v-if="ruleForm2.type==2">
                    <template v-for="(v,index) in ruleForm2.option">
                        <el-input placeholder="请输入选项内容" v-model="v.val">
                            <template slot="prepend">
                                <!--<el-radio v-model="ruleForm2.answer" :label="abc[index]"></el-radio>-->
                                <el-checkbox v-model="ruleForm2.answer2" :label="v.key"></el-checkbox>
                            </template>
                            <el-button slot="append" icon="el-icon-delete" style="color: red;" @click="del(v,index)"></el-button>
                        </el-input>
                    </template>
                    <i class="el-icon-circle-plus-outline"
                       style="font-size: 26px;color: #66b1ff;margin-top: 10px;" @click="pushAns"></i>
                    <div>正确答案：{{ruleForm2.answer2}}</div>
                </template>
            </el-form-item>
            <template v-if="ruleForm2.type=='3'">
                <el-form-item label="答案">
                    <el-radio-group v-model="ruleForm2.answer3">
                        <el-radio label="Y">正确</el-radio>
                        <el-radio label="N">错误</el-radio>
                    </el-radio-group>
                </el-form-item>
            </template>
            <template v-if="ruleForm2.type=='4'">
                <el-form-item label="答案(依次)">
                    <template v-for="(v,index) in ruleForm2.answer4">
                        <el-input type="text" :rows="5" auto-complete="off" v-model="v.key"></el-input>
                    </template>
                    <i class="el-icon-circle-plus-outline" @click="addAnswer4"
                       style="font-size: 26px;color: #66b1ff;margin-top: 10px;"></i>
                </el-form-item>
            </template>


            <el-form-item label="难度">
                <el-radio-group v-model="ruleForm2.difficulty">
                    <el-radio label="0">低</el-radio>
                    <el-radio label="1">中</el-radio>
                    <el-radio label="2">高</el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item label="总分数">
                <el-input type="text" v-model="ruleForm2.score" auto-complete="off"></el-input>
            </el-form-item>
            <el-form-item label="时长(秒)">
                <el-input type="text" v-model="ruleForm2.duration" auto-complete="off"></el-input>
            </el-form-item>
            <el-form-item label="答案数量">
                <el-input type="text" v-model="ruleForm2.answer_num" auto-complete="off"></el-input>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="submitForm('ruleForm2')">提交</el-button>
                <!--<el-button @click="getCheckedNodes">获取</el-button>-->
            </el-form-item>
        </el-form>
    </div>
</template>

<script>
    export default {
        components: {
        },
        name: "question-add",
        data () {
            var v1 = (rule, value, callback) => {
                if (value === '') {
                    callback(new Error('请输入题目内容'));
                } else if (value < 2 || value.length > 100) {
                    callback(new Error('2-100位'));
                } else {
                    callback();
                }
            };
            return {
                tree: [],
                defaultProps: {
                    children: 'children',
                    label: 'name'
                },
                abc: ['A','B','C','D','E','F','G','H','I','J','K','L','M','N'],
                ruleForm2: {
                    content: '',
                    type: '1', // 0单选 1多选

                    option: [{key: 'A', val: '',}, {key: 'B', val: '',}, {key: 'C', val: '',}, {key: 'D', val: '',}],
                    answer: '', // 单选答案
                    answer2: [], // 多选答案
                    answer3: '', // 多选答案
                    answer4: [''], // 多选答案
                    score: 1,
                    difficulty: '0', // 难度
                    duration: '60', // 时长（秒）
                    answer_num: '1', // 答案数量
                },
                rules2: {
                    content: [
                        {required: true, validator: v1, trigger: 'blur'}
                    ],
                    type: [
                        {required: true, trigger: 'blur'}
                    ],
                },
                questionId: '',
            }
        },
        props: ['pid', 'uid'],
        methods:{
            loadopen() {
                this.loading = this.$loading({
                    lock: true,
                    text: 'Loading',
                    spinner: 'el-icon-loading',
                    background: 'rgba(0, 0, 0, 0.2)'
                });
                setTimeout(() => {this.loading.close();}, 5000);
            },
            loadclose() {
                this.loading.close();
            },
            // 获取题目信息
            getInfo(row){
                // console.log('题目信息',row);
                // /admin/question/findById
                if(!row.id) {
                    this.ruleForm2.content = '';
                    this.ruleForm2.type = '0';
                    this.ruleForm2.option = [{key: 'A', val: '',}, {key: 'B', val: '',}, {key: 'C', val: '',}, {key: 'D', val: '',}];
                    this.ruleForm2.answer = '';
                    this.ruleForm2.answer2 = [];
                    this.ruleForm2.answer3 = '';
                    this.ruleForm2.answer4 = [{key: ''}];
                    this.ruleForm2.score = 1;
                    this.questionId = '';
                    return;
                }
                this.questionId = row.id;
                this.loadopen();
                this.config.post2('/admin/question/findById', {id: row.id}).then(res => {
                    this.loadclose();
                    if (res.data.code === '0') {
                        // console.log(res.data.question);
                        let qus = res.data.question;
                        this.ruleForm2.content = qus.content;
                        this.ruleForm2.type = qus.type;
                        let ar = [];
                        JSON.parse(qus.option||"[]").forEach((it,index)=>{
                            ar.push({key: this.abc[index], val: it[this.abc[index]]});
                        });
                        this.ruleForm2.option = ar;
                        if(qus.type==1){
                            this.ruleForm2.answer = JSON.parse(qus.right_answer)[0];
                        }else if(qus.type==2){
                            this.ruleForm2.answer2 = JSON.parse(qus.right_answer);
                        }else if(qus.type==3){
                            this.ruleForm2.answer3 = qus.right_answer;
                            console.log(this.ruleForm2.answer3)
                        }else if(qus.type==4){
                             let anr = [];
                            JSON.parse(qus.right_answer).forEach((i,dex)=>{
                                 anr.push({key: i})
                             });
                            this.ruleForm2.answer4 = anr;
                        }
                        this.ruleForm2.score = qus.score;
                        this.ruleForm2.difficulty = qus.difficulty;
                        this.ruleForm2.duration = qus.duration;
                        this.ruleForm2.answer_num = qus.answer_num;
                    } else {
                        this.$message.error(this.config.handleError(res.data));
                    }
                });
            },
            // 添加选项
            pushAns(){
                let index = this.ruleForm2.option.length;
                let key = this.abc[index];
                this.ruleForm2.option.push({
                    key: key,
                    val: ''
                })
            },
            // 添加填空题答案
            addAnswer4(){
                this.ruleForm2.answer4.push({key: ''});
            },
            // 删除选项
            del(v,index){
                this.ruleForm2.option.splice(index,1);
                this.ruleForm2.answer = '';
                this.ruleForm2.answer2 = [];
            },
            // 提交前验证
            valid2(){
                let flag = true;
                if(!this.ruleForm2.content) flag = false;
                if(this.ruleForm2.type==2){
                    if(!this.ruleForm2.answer2.length){
                        flag = false;
                    }
                }else if(this.ruleForm2.type==1){
                    if(!this.ruleForm2.answer){
                        flag = false;
                    }
                }else if(this.ruleForm2.type==3){
                    if(!this.ruleForm2.answer3){
                        flag = false;
                    }
                }else if(this.ruleForm2.type==4){
                    console.log(this.ruleForm2.answer4)
                    if(!this.ruleForm2.answer4[0]){
                        flag = false;
                    }
                }
                return flag;
            },
            submitForm(formName) {
                if(!this.valid2()) return;
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        let arr = [],ans=[];  // arr选项集合; ans答案集合;
                        this.ruleForm2.option.forEach((it,index)=>{
                            let key = this.abc[index];
                            arr[index] = {};
                            arr[index][key]=it.val;
                        });
                        if(this.ruleForm2.type==2){
                            ans = this.ruleForm2.answer2;
                        }else if(this.ruleForm2.type==1){
                            ans = [this.ruleForm2.answer];
                        }else if(this.ruleForm2.type==3){
                            ans = this.ruleForm2.answer3;
                            arr = [];
                        }else if(this.ruleForm2.type==4){
                            this.ruleForm2.answer4.forEach(it=>{
                                ans.push(it.key);
                            });
                            arr = [];
                        }
                        let obj = {
                            'question.question_back_id': this.pid,
                            'question.id': this.questionId,
                            'question.content': this.ruleForm2.content,
                            'question.type': this.ruleForm2.type,
                            'question.option': JSON.stringify(arr),
                            'question.right_answer': this.ruleForm2.type==3?ans:JSON.stringify(ans),
                            'question.difficulty': this.ruleForm2.difficulty,
                            'question.score': this.ruleForm2.score,
                            'question.duration': this.ruleForm2.duration,
                            'question.answer_num': this.ruleForm2.answer_num,
                        };
                        // console.log(obj); return;
                        let url = this.questionId ? '/admin/question/update' : '/admin/question/add';
                        this.loadopen();
                        //-----------------------------------------------------------------------
                        this.config.post2(url, obj).then(res => {
                            this.loadclose();
                            if (res.data.code === '0') {
                                this.$message({
                                    message: res.data.message,
                                    type: 'success'
                                });
                            } else {
                                this.$message.error(this.config.handleError(res.data));
                            }
                            this.$emit('done', '');
                        });
                    } else {
                        console.log('error submit!!');
                        return false;
                    }
                });
            },
        },
        mounted(){
            console.log(this.pid, this.uid, 'ff')
        }
    }
</script>

<style scoped>

</style>
